package vn.anhqn.englishsentensetranslator.SentenseLookup;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.memetix.mst.language.Language;

import vn.anhqn.englishsentensetranslator.R;
import vn.anhqn.englishsentensetranslator.SentenseLookup.DialogConfirmDelete.confirmDeleteListener;
import vn.anhqn.englishsentensetranslator.SentenseLookup.DialogDeleteCatAction.ISelectTypeDelete;
import vn.anhqn.englishsentensetranslator.SentenseLookup.DialogSentenseAction.menuSentenseListener;
import vn.anhqn.englishsentensetranslator.adapter.CategorySpinnerAdapter;
import vn.anhqn.englishsentensetranslator.adapter.SentenseAdapter;
import vn.anhqn.englishsentensetranslator.addsentense.AddCatDialog;
import vn.anhqn.englishsentensetranslator.addsentense.AddSentenseFragment;
import vn.anhqn.englishsentensetranslator.addsentense.AddCatDialog.AddCatListener;
import vn.anhqn.englishsentensetranslator.base.fragment.FragmentHaveSlidingMenu;
import vn.anhqn.englishsentensetranslator.constant.ConfigApp;
import vn.anhqn.englishsentensetranslator.constant.Constant;
import vn.anhqn.englishsentensetranslator.model.Category;
import vn.anhqn.englishsentensetranslator.model.Sentense;
import vn.anhqn.englishsentensetranslator.utils.PreferenceHelper;
import vn.anhqn.englishsentensetranslator.utils.SqliteHelper;
import vn.anhqn.englishsentensetranslator.utils.StringUtils;
import vn.anhqn.englishsentensetranslator.utils.Utils;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class SentenseListFragment extends FragmentHaveSlidingMenu implements TextWatcher, OnItemSelectedListener, OnItemClickListener,
		OnItemLongClickListener, AddCatListener {

	private ListView lvSentense;
	private SentenseAdapter adapter;
	private List<Sentense> sentenseList;
	private List<Sentense> fillSentenseList;
	private List<Sentense> fillCatList;
	private SqliteHelper sqliteHelper;
	private EditText editSearch;
	private Spinner catSpinner;
	private CategorySpinnerAdapter catAdapter;
	private List<Category> listCat = new ArrayList<Category>();
	private Language currentLang = Language.ENGLISH;

	@Override
	public void setBerhaviorView(View mView) {
		lvSentense = (ListView) mView.findViewById(R.id.lv_sentense);
		editSearch = (EditText) mView.findViewById(R.id.edit_search);
		catSpinner = (Spinner) mView.findViewById(R.id.spin_categories);
		editSearch.addTextChangedListener(this);
		mView.findViewById(R.id.imv_remove_cat).setOnClickListener(this);
		mView.findViewById(R.id.imv_edit_cat).setOnClickListener(this);
		currentLang = getCurrentLang();
		initFirstData();

	}

	private void initFirstData() {
		sentenseList = new ArrayList<Sentense>();
		fillSentenseList = new ArrayList<Sentense>();
		fillCatList = new ArrayList<Sentense>();
		sqliteHelper = new SqliteHelper(getActivity());
		// init category spiner
		if (sqliteHelper.getCategory(1) == null)
			sqliteHelper.addCategory(new Category(0, getActivity().getResources().getString(R.string.default_cat)));

		listCat.clear();
		listCat.addAll(sqliteHelper.getAllCategory());
		listCat.add(0, new Category(-1, getActivity().getResources().getString(R.string.all)));
		catAdapter = new CategorySpinnerAdapter(listCat, getActivity());
		catSpinner.setAdapter(catAdapter);
		int prePos = PreferenceHelper.getInstance(getActivity()).getInt(Constant.KEY_EXTRA_POSITION_CAT_SENTENSE_LIST, -1);
		if (prePos < listCat.size() && prePos != -1)
			catSpinner.setSelection(prePos);
		catSpinner.setOnItemSelectedListener(this);
		Bundle bundle = getArguments();
		sentenseList.clear();
		sentenseList.addAll(sqliteHelper.getAllSentensesEtoY());
		fillSentenseList.addAll(sentenseList);
		adapter = new SentenseAdapter(fillSentenseList, getActivity());
		lvSentense.setAdapter(adapter);
		lvSentense.setOnItemClickListener(this);
		lvSentense.setOnItemLongClickListener(this);

	}

	@Override
	public int getResLayout() {
		return R.layout.sentense_list_fragment;
	}

	@Override
	public int getidTitle() {
		return R.string.sentense_list_title;
	}

	private Language getCurrentLang() {
		int indexLang = PreferenceHelper.getInstance(getActivity()).getInt(ConfigApp.PREFERENCES_LANGUAGE_INDEX, 0);
		return Language.fromIndex(indexLang);
	}

	private void fillBySearch(CharSequence query) {

		fillSentenseList.clear();
		for (Sentense sentense : fillCatList) {
			String fromLang = sentense.getFromLang().toLowerCase(Locale.ROOT);
			String toLang = sentense.getToLang().toLowerCase(Locale.ROOT);

			if (currentLang == Language.VIETNAMESE | currentLang == Language.FRENCH) {
				fromLang = StringUtils.getInstance().convertNonSmear(fromLang.toString());
				toLang = StringUtils.getInstance().convertNonSmear(toLang.toString());
			}
			if (fromLang.contains(query) | toLang.contains(query))
				fillSentenseList.add(sentense);
		}
	}

	private void fillByCategory(int idCat) {
		fillCatList.clear();
		if (idCat != -1)
			for (Sentense sentense : sentenseList) {
				if (sentense.getIdCategory() == idCat)
					fillCatList.add(sentense);
			}
		else {
			fillCatList.addAll(sentenseList);
		}
	}

	@Override
	public void onClickView(View v) {
		int idView = v.getId();
		switch (idView) {
		case R.id.imv_remove_cat:
			DialogDeleteCatAction dialogDeleteCat = new DialogDeleteCatAction(getActivity());
			dialogDeleteCat.setActionListener(new ISelectTypeDelete() {

				@Override
				public void onDeteteSelectDelete() {

				}

				/*@Override
				public void onDeleteSentenseCat() {
					DialogConfirmDelete dialogConfirm = new DialogConfirmDelete(getActivity());
					dialogConfirm.setListener(new confirmDeleteListener() {

						@Override
						public void onOK() {
							if (catSpinner.getSelectedItemPosition() > 0) {
								sqliteHelper.deleteCategory(catAdapter.getItem(catSpinner.getSelectedItemPosition()));
								sqliteHelper.deleteEtoYSentenseByIdCat(catAdapter.getItem(catSpinner.getSelectedItemPosition())
										.getId());
								listCat.remove(catAdapter.getItem(catSpinner.getSelectedItemPosition()));
								catAdapter.notifyDataSetChanged();
								sentenseList.removeAll(fillCatList);
								catSpinner.setSelection(0);

							} else {
								sqliteHelper.deleteAllSentenseEtoY();
								sentenseList.clear();
								fillCatList.clear();
								fillSentenseList.clear();
								adapter.notifyDataSetChanged();
							}

						}
					});
					dialogConfirm.show();
				}*/

				@Override
				public void onDeleteCat() {
					if (catSpinner.getSelectedItemPosition() == 0) {
						Toast.makeText(getActivity(), R.string.sentense_list_menu_select_cat_to_del, Toast.LENGTH_SHORT).show();
					} else if (catSpinner.getSelectedItemPosition() == 1) {
						Toast.makeText(getActivity(), R.string.sentense_list_menu_cant_del_default_cat, Toast.LENGTH_SHORT).show();

					} else {
						DialogConfirmDelete dialogConfirm = new DialogConfirmDelete(getActivity());
						dialogConfirm.setListener(new confirmDeleteListener() {

							@Override
							public void onOK() {
								if (catSpinner.getSelectedItemPosition() > 1) {
									sqliteHelper.deleteCategory(catAdapter.getItem(catSpinner.getSelectedItemPosition()));
									listCat.remove(catAdapter.getItem(catSpinner.getSelectedItemPosition()));
									catAdapter.notifyDataSetChanged();
									catSpinner.setSelection(0);
								}
							}
						});
						dialogConfirm.show();
					}
				}
			});
			dialogDeleteCat.show();
			break;
		case R.id.imv_edit_cat:
			if (catSpinner.getSelectedItemPosition() == 0) {
				Toast.makeText(getActivity(), R.string.sentense_list_menu_select_cat_to_edit, Toast.LENGTH_SHORT).show();
			}/* else if (catAdapter.getItem(catSpinner.getSelectedItemPosition()).getId() == 1) {
				Toast.makeText(getActivity(), R.string.sentense_list_menu_cant_edit_default_cat, Toast.LENGTH_SHORT).show();
			}*/ else {
				AddCatDialog dialog2 = new AddCatDialog(getActivity());
				dialog2.setAddListener(this);
				dialog2.setEditCat(catAdapter.getItem(catSpinner.getSelectedItemPosition()));
				dialog2.show();
			}
			break;

		default:
			break;
		}
	}

	private void deleteCat() {
		listCat.remove(catSpinner.getSelectedItemPosition());
		sqliteHelper.deleteCategory(catAdapter.getItem(catSpinner.getSelectedItemPosition()));
		sqliteHelper.deleteAllCategory();
		catAdapter.notifyDataSetChanged();
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (s != null) {
			fillBySearch(s);
			adapter.notifyDataSetChanged();
		}

	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		int idCat = catAdapter.getItem(position).getId();
		fillByCategory(idCat);
		PreferenceHelper.getInstance(getActivity()).putInt(Constant.KEY_EXTRA_POSITION_CAT_SENTENSE_LIST, position);
		fillBySearch(editSearch.getText().toString());
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		DialogSentenseAction actionDialog = new DialogSentenseAction(getActivity());
		actionDialog.setActionListener(new menuSentenseListener() {

			@Override
			public void onEdit() {
				Sentense sentense = adapter.getItem(position);
				Bundle bundle = new Bundle();
				bundle.putBoolean(Constant.KEY_EXTRA_IS_FINISH, true);
				bundle.putString(Constant.KEY_EXTRA_FROM_TEXT, sentense.getFromLang());
				bundle.putString(Constant.KEY_EXTRA_TO_TEXT, sentense.getToLang());
				bundle.putInt(Constant.KEY_EXTRA_SENTENSE_ACTION, Constant.EDIT);
				bundle.putInt(Constant.KEY_EXTRA_SENTENSE_ID,sentense.getId());
				bundle.putInt(Constant.KEY_EXTRA_CAT_ID, sentense.getIdCategory());
				replaceNewInstance(AddSentenseFragment.class, bundle);
			}

			@Override
			public void onDelete() {
				DialogConfirmDelete dialogConfirm = new DialogConfirmDelete(getActivity());
				dialogConfirm.setListener(new confirmDeleteListener() {
					@Override
					public void onOK() {
						Sentense sentense = adapter.getItem(position);
						sqliteHelper.deleteSentenseEtoY(sentense);
						fillSentenseList.remove(sentense);
						sentenseList.remove(sentense);
						fillCatList.remove(sentense);
						adapter.notifyDataSetChanged();
					}
				});
				dialogConfirm.show();
			}

			@Override
			public void onCopy() {
				Utils.getIntance().copyTextToClipboad(getActivity(), adapter.getItem(position).getFromLang(), R.string.copy_messege);
			}

			@Override
			public void onShare() {
				Utils.getIntance().startActivityChooser(getActivity(), adapter.getItem(position).getFromLang());
			}
		});
		actionDialog.show();
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.menu_sentense_item, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return super.onContextItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Bundle bundle = new Bundle();
		bundle.putSerializable(Constant.KEY_EXTRA_SENTENSE, adapter.getItem(position));
		replaceNewInstance(SentenseDetail.class, bundle);
	}

	@Override
	public void onAddClick(String catName) {

	}

	@Override
	public void onEdit(Category cat) {

		catAdapter.getItem(catSpinner.getSelectedItemPosition()).setName(cat.getName());
		sqliteHelper.updateCategory(cat);
		catAdapter.notifyDataSetChanged();
	}

}
